﻿using System;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.ViewModels.ReadMeter;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    ///     水表指令
    /// </summary>
    [Authorize]
    public class MeterCommandsController : BaseApiController
    {
        private static ILogger<MeterCommandsController> _logger;
        private readonly IAccountManageLogic _accountManageLogic;
        private readonly IBaseInfoLogic _baseStatistcsLogic;
        private readonly IMeterCommandsLogic _meterCommandsLogic;
        private readonly TokenHelper _tokenHelper;

        /// <inheritdoc />
        public MeterCommandsController(
            ILogger<MeterCommandsController> logger,
            IBaseInfoLogic baseInfoLogic,
            IAccountManageLogic accountManageLogic,
            IMeterCommandsLogic meterCommandsLogic,
            TokenHelper tokenHelper)
        {
            _logger = logger;
            _baseStatistcsLogic = baseInfoLogic;
            _accountManageLogic = accountManageLogic;
            _meterCommandsLogic = meterCommandsLogic;
            _tokenHelper = tokenHelper;
        }

        /// <summary>
        ///     读取抄表数据
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Meter/Meters")]
        public IActionResult GetMeters([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息
            try
            {
                //获取所有查询条件
                var aid = obj.aid.ToString();
                var page = Convert.ToInt32(obj.page.ToString());
                var searchType = obj.searchType.ToString();
                var searchValue = obj.searchValue.ToString();
                if (aid == token.payload.areaid)
                    aid = "";
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok",
                    data = _meterCommandsLogic.GetMeters(aid, page, token.payload.id, token.payload.areaid,searchType, searchValue)
                });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     查询预制发送命令
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Meter/Commands")]
        public IActionResult GetCommands([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //验证用户信息

            try
            {
                ////获取所有查询条件
                //var statusType = obj.status.ToString();
                //var searchType = obj.searchType.ToString();
                //var searchValue = obj.searchValue.ToString();
                //var aid = obj.aid.ToString();
                string meterNumber = obj.meterNumber.ToString();
                var page = Convert.ToInt32(obj.page.ToString());
                //if (aid == token.payload.areaid)
                //    aid = "";
                return Ok(new
                {
                    errcode = 0,
                    msg = "ok",
                    data = _meterCommandsLogic.GetCommand(meterNumber, page, token.payload.id)
                });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }


        /// <summary>
        ///     添加抄表指令--执行抄表指令
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Meter/Commands/Read")]
        public IActionResult SetCommandRead([FromBody] BaseMeterCommandPost obj)
        {
            try
            {
                _logger.LogInformation("开始添加抄表指令");
                if (_meterCommandsLogic.SameCommand(obj.meterNumber, 1))
                    return Ok(new {errcode = 0, msg = "ok"});
                var result = _meterCommandsLogic.SetReadCommand(obj.meterNumber, CommandType.抄表指令);
                return Ok(result
                    ? new {errcode = 0, msg = "ok"}
                    : new {errcode = 1, msg = "添加抄表指令失败"});
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"添加抄表指令失败,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 添加开关阀指令
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Meter/Commands/Tap")]
        public IActionResult SetCommandTap([FromBody] ValueCommandPost obj)
        {
            try
            {
                //保存指令
                //if (_meterCommandsLogic.SameCommand(obj.meterNumber, tap)) { 
                //    return Ok(new { errcode = 0, msg = "ok" });
                //}
                int tap = obj.tapType;
                _meterCommandsLogic.SameCommand(obj.meterNumber, tap);
                var result = _meterCommandsLogic.SetValveCommand(obj.CTdeviceId,  tap);
                return Ok(result
                    ? new {errcode = 0, msg = "ok"}
                    : new {errcode = 1, msg = $"添加开关阀指令失败"});
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"添加开关阀指令失败,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        ///     撤销未发送指令
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Meter/Commands/Cancel")]
        public IActionResult DeleteCommand([FromBody] dynamic obj)
        {
            try
            {
                string cid = obj.commandId.ToString();
                var result = _meterCommandsLogic.DeleteCommand(cid);
                return Ok(result
                    ? new {errcode = 0, msg = "ok"}
                    : new {errcode = 1, msg = $"撤销数据失败"});
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"撤销数据失败,错误:{e.Message}"
                });
            }
        }
    }
}